package com.xinbochuang.machine.admin.controller.api;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xinbochuang.machine.admin.domain.system.SysUser;
import com.xinbochuang.machine.admin.dto.AesRequestBean;
import com.xinbochuang.machine.admin.service.system.ISysUserService;
import com.xinbochuang.machine.common.constant.UserConstants;
import com.xinbochuang.machine.common.controller.BaseController;
import com.xinbochuang.machine.common.utils.AESUtils;
import com.xinbochuang.machine.common.utils.SecurityUtils;
import com.xinbochuang.machine.framework.web.domain.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * app用户接口
 *
 * @author 黄晓鹏
 * @date 2020-09-25 15:51
 */
@Api(value = "app用户接口", position = 100, protocols = "http")
@RestController
@Validated
@RequestMapping("/api/user")
public class AppUserController extends BaseController {

    @Resource
    private ISysUserService userService;

    private static final String DEFAULT_PWD = "123456";

    /**
     * 根据用户id获取用户信息
     *
     * @param userId 用户id
     * @return 用户信息
     */
    @ApiOperation(value = "根据用户id获取用户信息", consumes = "application/json", response = AjaxResult.class)
    @GetMapping("/{userId}")
    public AjaxResult info(@PathVariable("userId") Integer userId) {
        return AjaxResult.data(userService.info(userId));
    }

    /**
     * 根据条件查询用户
     *
     * @param user 条件信息
     * @return 用户集合
     */
    @ApiOperation(value = "根据条件查询用户(账号/昵称/手机号/部门id)", consumes = "application/json", response = AjaxResult.class)
    @PostMapping("/query")
    public AjaxResult query(@RequestBody SysUser user) {
        return AjaxResult.data(userService.selectByParams(user));
    }

    /**
     * app添加用户
     *
     * @param user 用户
     * @return 结果
     */
    @ApiOperation(value = "添加用户", consumes = "application/json", response = AjaxResult.class)
    @PostMapping("addUser")
    public AjaxResult add(@RequestBody SysUser user) {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUsername()))) {
            return AjaxResult.error("新增用户'" + user.getUsername() + "'失败，登录账号已存在");
        } else if (StrUtil.isNotBlank(user.getIdCard()) && UserConstants.NOT_UNIQUE.equals(userService.checkIdCardUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUsername() + "'失败，身份证号码已存在");
        } else if (StrUtil.isNotBlank(user.getPhone()) && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUsername() + "'失败，手机号码已存在");
        }
        StringBuilder sb = new StringBuilder();
        if (StrUtil.isBlank(user.getUsername())) {
            //创建用户名
            if (StrUtil.isBlank(user.getNickname())) {
                return AjaxResult.error("昵称不能为空！");
            }
            //查询此姓名数量
            int num = userService.count(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getNickname, user.getNickname()));
            //生成账号
            String userName = PinyinUtil.getPinyin(user.getNickname(), "") + (num == 0 ? "" : num + 1);
            user.setUsername(userName);
            if (StrUtil.isNotBlank(sb.toString())) {
                sb.append(",");
            }
            sb.append("账号：").append(user.getUsername());
        }
        if (StrUtil.isNotBlank(user.getPassword())) {
            user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        } else {
            user.setPassword(SecurityUtils.encryptPassword(DEFAULT_PWD));
            sb.append("密码：").append(DEFAULT_PWD);
        }
        user.setCreateTime(DateUtil.now());
        if (userService.insertUser(user)) {
            return AjaxResult.ok(sb.toString());
        } else {
            return AjaxResult.error();
        }
    }


    /**
     * app添加用户
     *
     * @return 结果
     */
    @ApiOperation(value = "添加用户", consumes = "application/json", response = AjaxResult.class)
    @PostMapping("addUserN")
    public AjaxResult addN(@RequestBody AesRequestBean aesRequestBean) {
        String data = aesRequestBean.getData();
        data=AESUtils.decode(data);
        SysUser user= JSON.parseObject(data,SysUser.class);
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUsername()))) {
            return AjaxResult.error("新增用户'" + user.getUsername() + "'失败，登录账号已存在");
        } else if (StrUtil.isNotBlank(user.getIdCard()) && UserConstants.NOT_UNIQUE.equals(userService.checkIdCardUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUsername() + "'失败，身份证号码已存在");
        } else if (StrUtil.isNotBlank(user.getPhone()) && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUsername() + "'失败，手机号码已存在");
        }
        StringBuilder sb = new StringBuilder();
        if (StrUtil.isBlank(user.getUsername())) {
            //创建用户名
            if (StrUtil.isBlank(user.getNickname())) {
                return AjaxResult.error("昵称不能为空！");
            }
            //查询此姓名数量
            int num = userService.count(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getNickname, user.getNickname()));
            //生成账号
            String userName = PinyinUtil.getPinyin(user.getNickname(), "") + (num == 0 ? "" : num + 1);
            user.setUsername(userName);
            if (StrUtil.isNotBlank(sb.toString())) {
                sb.append(",");
            }
            sb.append("账号：").append(user.getUsername());
        }
        if (StrUtil.isNotBlank(user.getPassword())) {
            user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        } else {
            user.setPassword(SecurityUtils.encryptPassword(DEFAULT_PWD));
            sb.append("密码：").append(DEFAULT_PWD);
        }
        user.setCreateTime(DateUtil.now());
        if (userService.insertUser(user)) {
            return AjaxResult.ok("");
        } else {
            return AjaxResult.error();
        }
    }
    /**
     * app修改用户
     *
     * @param user 用户
     * @return 结果
     */
    @ApiOperation(value = "根据用户id修改用户", consumes = "application/json", response = AjaxResult.class)
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @PutMapping
    public AjaxResult updateById(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        if (StrUtil.isNotBlank(user.getIdCard()) && UserConstants.NOT_UNIQUE.equals(userService.checkIdCardUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUsername() + "'失败，身份证号码已存在");
        } else if (StrUtil.isNotBlank(user.getPhone()) && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUsername() + "'失败，手机号码已存在");
        } else if (StrUtil.isNotBlank(user.getEmail()) && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUsername() + "'失败，邮箱账号已存在");
        }
        user.setUpdateTime(DateUtil.now());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 根据用户id/状态字段，启用/禁用用户
     *
     * @param user 用户信息
     * @return 结果
     */
    @ApiOperation(value = "根据用户id/状态字段，启用/禁用用户", consumes = "application/json", response = AjaxResult.class)
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        return toAjax(userService.updateById(user));
    }

}
